<template>
  <el-dialog :visible.sync="visible" :before-close="handleCloseDialog" title="编辑信息" width="30%">
    <span v-if="userInfo.user_id">
      <el-form ref="dataForm" :model="userForm" :rules="formRules" label-width="100px" label-position="left">

        <el-form-item label="账号" prop="user_id">
          <el-input v-model="userForm.user_id" placeholder="例：0602140119(学号)"/>
        </el-form-item>

        <el-form-item label="姓名" prop="user_name">
          <el-input v-model="userForm.user_name" placeholder="请填写真实姓名"/>
        </el-form-item>

        <el-form-item label="性别" prop="sex">
          <el-radio-group v-model="userForm.sex">
            <el-radio label="男">男</el-radio>
            <el-radio label="女">女</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item v-if="userForm.role_id === '学生'" label="在校状态" prop="zxzt">
          <el-radio-group v-model="userForm.zxzt">
            <el-radio label="在校">在校</el-radio>
            <el-radio label="不在校">不在校</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="用户组" prop="role_id">
          <el-select v-model="userForm.role_id" placeholder="请选择">
            <el-option
              v-for="item in userGroupConfig"
              :key="item.role_id"
              :label="item.role_name"
              :value="item.role_name"/>
          </el-select>
        </el-form-item>
        <span v-if="userForm.role_id === '学生'">
          <el-form-item label="系部" prop="depa">
            <el-select v-model="userForm.depa" placeholder="请选择">
              <el-option
                v-for="item in config.departmentOptions"
                :key="item.value"
                :label="item.label"
                :value="item.label"/>
            </el-select>
          </el-form-item>

          <el-form-item label="班级" prop="bmmc">
            <el-input v-model="userForm.bmmc" placeholder="例：“软件1701”"/>
          </el-form-item>

          <el-form-item label="年级" prop="grade">
            <el-input v-model="userForm.grade" placeholder="例：2017级填写“2017”"/>
          </el-form-item>
        </span>

        <span v-else>
          <el-form-item label="部门" prop="bmmc">
            <el-input v-model="userForm.bmmc" placeholder="例：“电力工程系”"/>
          </el-form-item>
        </span>

        <el-checkbox v-model="editPwd">重置密码（注：重置后密码默认为登录账号）</el-checkbox>

      </el-form>
    </span>

    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="handleEditUser">提交</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { getRoleList, updateUser } from '@/api/user'
import config from '@/utils/config.js'
import md5 from 'md5'
import { isvalidUserId } from '@/utils/validate'

export default {
  name: 'EditUserDialog',
  props: {
    visible: {
      type: Boolean,
      required: true
    },
    userInfo: {
      type: Object,
      required: true
    }
  },
  data() {
    const validateUsername = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请填写账号'))
      } else if (!isvalidUserId(value)) {
        callback(new Error('请输入正确的账号'))
      } else {
        callback()
      }
    }
    const validatePass = (rule, value, callback) => {
      if (!value) {
        callback('请填写密码')
      } else if (value.length < 6) {
        callback(new Error('密码不能小于6位'))
      } else {
        callback()
      }
    }
    return {
      config,
      userForm: {},
      userGroupConfig: [],
      formRules: {
        user_id: [{ required: true, trigger: 'blur', validator: validateUsername }],
        user_name: [{ required: true, trigger: 'blur', message: '请填写姓名' }],
        sex: [{ required: true, trigger: 'blur', message: '请填写性别' }],
        role_id: [{ required: true, trigger: 'blur', message: '请选择用户组' }],
        depa: [{ required: true, trigger: 'blur', message: '请选择所在系部' }],
        bmmc: [{ required: true, trigger: 'blur', message: '请填写所在班级' }],
        grade: [{ required: true, trigger: 'blur', message: '请填写所在学年' }],
        zxzt: [{ required: true, trigger: 'blur', message: '请填写在线状态' }],
        user_pwd: [{ required: true, trigger: 'blur', validator: validatePass }]
      },
      editPwd: false
    }
  },
  watch: {
    userInfo: function(val) {
      this.userForm = val
      this.userForm.role_id = (() => {
        const roleName = this.userGroupConfig
          .filter(item => {
            return item.role_id === this.userForm.role_id
          })[0]
          .role_name
        return roleName || this.userForm.role_id
      })()
    }
  },
  created() {
    getRoleList().then(res => {
      this.userGroupConfig = res.data
    })
  },
  methods: {
    handleCloseDialog() {
      this.$emit('close')
      this.$refs.dataForm.resetFields()
    },
    handleEditUser() {
      this.$refs.dataForm.validate(valid => {
        if (!valid) {
          return
        }
        // this.formateUserData(this.userForm)
        updateUser(this.formateUserData(this.userForm)).then(res => {
          let messageType = 'error'

          if (res.code === 200) {
            messageType = 'success'
            this.$emit('submit')
            this.$refs.dataForm.resetFields()
          }

          this.$message({
            type: messageType,
            message: res.msg
          })
        })
      })
    },
    formateUserData(data) {
      const res = Object.assign({}, data)
      res.role_id = res.role_id.toString()
      res.id = res.id.toString()

      if (res.role_id === '学生') {
        res.depa = res.depa.toString()
        res.grade = res.grade.toString()
      } else {
        res.depa = '-'
        res.grade = '0000'
      }

      if (this.editPwd) {
        res.user_pwd = md5(res.user_id)
      }
      return res
    }
  }
}
</script>

<style scoped>

</style>
